//
//  MBDMessageViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/11/7.
//

import Foundation
import UIKit
import MJRefresh
import Toast_Swift

class MBDMessageViewController : MBDBaseViewController {
    var tableView = UITableView()
    
    var viewModel = MBDMessageViewModel()
    var pageIndex : Int!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.pageIndex = 1

        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.allowsMultipleSelection = false
        tableView.allowsSelectionDuringEditing = false
        tableView.allowsMultipleSelectionDuringEditing = false
        self.view.addSubview(tableView)
        
        NSLayoutConstraint.activate([
        self.view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: tableView.topAnchor),
                    self.view.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
                    self.view.leadingAnchor.constraint(equalTo: tableView.leadingAnchor),
                    self.view.trailingAnchor.constraint(equalTo: tableView.trailingAnchor),
                ])
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.rowHeight = 100
        
        tableView.register(MBDMessageCell.self, forCellReuseIdentifier: "MBDMessageCell")
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            [unowned self] in
            guard MBDAccountInfoModel.current() != nil else {
                self.view.makeToast("请先登录",position: .center)
                self.tableView.mj_header?.endRefreshing()
                self.pageIndex = 1
                self.tableView.mj_footer?.resetNoMoreData()
                return
            }
            
            self.pageIndex = 1
            self.tableView.mj_footer?.resetNoMoreData()
            
            viewModel.doRequest { error,result,totalPage in
                
                if nil != error {
                    self.view.makeToast(error?.localizedDescription,position: .center)
                } else {
                    self.viewModel.cellModels = result
                    self.tableView.reloadData()
                                    
                    self.tableView.mj_header?.endRefreshing()
                    if self.pageIndex >= totalPage {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.resetNoMoreData()
                    }
                }
            }
        })
        
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            [unowned self] in
            
            guard MBDAccountInfoModel.current() != nil else {
                self.view.makeToast("请先登录",position: .center)
                self.tableView.mj_header?.endRefreshing()
                self.pageIndex = 1
                self.tableView.mj_footer?.resetNoMoreData()
                return
            }
            
            self.pageIndex += 1
            viewModel.doRequest { error,result,totalPage in
                
                if nil != error {
                    self.view.makeToast(error?.localizedDescription,position: .center)
                } else {
                    var msgs = Array<MBDMessageCellModel>()
                    msgs.append(contentsOf: self.viewModel.cellModels ?? Array<MBDMessageCellModel>())
                    
                    if result?.count ?? 0 > 0 {
                        msgs.append(contentsOf: result!)
                    }
                    
                    self.viewModel.cellModels = msgs
                    self.tableView.reloadData()
                    
                    self.tableView.mj_footer?.endRefreshing()
                    
                    if self.pageIndex >= totalPage {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    }
                }
            }
        })
        
        if MBDAccountInfoModel.current() != nil {
            refreshUI()
        }
        
        tableView.setDynamicBackgroundColor()
        view.setDynamicBackgroundColor()
    }
    
    override func updateColors() {
        super.updateColors()
        
        tableView.setDynamicBackgroundColor()
        
        if let current = MBDAccountInfoModel.current() {
            // 遍历并更新 cellModels
            if let cellModels = self.viewModel.cellModels {
                for i in 0..<cellModels.count {
                    let message = cellModels[i].message
                    
                    // 重新设置 message
                    self.viewModel.cellModels?[i].message = message
                }
            }
            
            self.tableView.reloadData()
        } else {
            
        }
    }
    
}

extension MBDMessageViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let count = self.viewModel.cellModels?.count ?? 0
        return count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cellModel = self.viewModel.cellModels![indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "MBDMessageCell", for: indexPath)
        (cell as! MBDMessageCell ).cellModel = cellModel
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        let realCellModel = cellModel as! MBDMessageCellModel
        let messageId  = realCellModel.message!.messageId
        let vc = UIAlertController(title: nil, message: "确定删除？", preferredStyle: UIAlertController.Style.alert)
        let confirmAction = UIAlertAction(title: "确认", style: UIAlertAction.Style.default) { UIAlertAction in
            
        }
        
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel)
        vc.addAction(cancelAction)
        vc.addAction(confirmAction)
        self.present(vc, animated: true)
    }
    
    func refreshUI() {
        self.pageIndex = 1
        viewModel.doRequest { error,result,totalPage in
            
            if nil != error {
                self.view.makeToast(error?.localizedDescription,position: .center)
            } else {
                self.viewModel.cellModels = result
                self.tableView.reloadData()
                self.tableView.mj_header?.endRefreshing()
                
                if(0 == result?.count) {
                    self.tableView.setEmptyView(title: "您没有任何消息",
                                                       message: "恭喜你")
                } else {
                    self.tableView.restore()
                }
                
                if totalPage == 1 {
                    self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                } else {
                    self.tableView.mj_footer?.resetNoMoreData()
                }
            }
        }
    }
    

    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        return (cellModel as! MBDMessageCellModel).cellHeight
    }
    
}


extension MBDMessageViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cellModel = self.viewModel.cellModels![indexPath.row]
//        let viewModel = MBDUploadGroupViewModel(groupDetail: cellModel.groupDetail,isUpdate: true)
//        let modifyVC = MBDUploadGroupViewController(viewModel: viewModel)
//        self.navigationController?.pushViewController(modifyVC, animated: true)

//        let vc = MBDMsgDetailViewController()
//        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}
